from backend.backend import Backend
from workflow.task import Task
# from workflow.result import Result # uncomment this line if using Result objects (not needed in simple workflow)
from workflow.flowData import Status
from vars import *

class StoreBackend(Backend):
   
    def __init__(self): 
        Backend.__init__(self, WorkflowName)  # be sure you update the workflow name

    def wire(self):
        self.register_result_listener(Role.Customer, Step.PlaceOrder, self.CreateInventoryCheckTask)
        self.register_result_listener(Role.InventoryMgr, Step.CheckInventory, self.CreateFulfillOrderTask)
        self.register_result_listener(Role.PackagePackager, Step.PackageShipment, self.CreateDeliveryTask)
        self.register_result_listener(Role.TruckDriver, Step.Delivery, self.MarkPackageDelivered)
        self.register_result_listener(Role.Customer, Step.ChooseBackorder, self.MarkPackageDelivered)
        
    def CreateInventoryCheckTask(self, results):  
    #This will be called (aka: it will run) after "aRoleName" completes "aStepName"
        for result in results:  # repeat the following actions for each result
            task = Task.construct_from_result(result, Role.InventoryMgr, Step.CheckInventory)
            self.workflow.add(task) # add the new task to the workflow
            self.workflow.update_status(result, Status.COMPLETE)
            
    def CreateFulfillOrderTask(self, results):  
    #This will be called (aka: it will run) after "aRoleName" completes "aStepName"
        for result in results:  # repeat the following actions for each result
            if result.data['instock'] == "No":
                task = Task.construct_from_result(result, Role.Customer, Step.ChooseBackorder)
            elif result.data['instock'] == "Yes":
                task = Task.construct_from_result(result, Role.PackagePackager, Step.PackageShipment)
            self.workflow.add(task) # add the new task to the workflow
            self.workflow.update_status(result, Status.COMPLETE)

    def CreateDeliveryTask(self, results):  
    #This will be called (aka: it will run) after "aRoleName" completes "aStepName"
        for result in results:  # repeat the following actions for each result
            task = Task.construct_from_result(result, Role.TruckDriver, Step.Delivery)
            self.workflow.add(task) # add the new task to the workflow
            self.workflow.update_status(result, Status.COMPLETE)
            
    def MarkPackageDelivered(self, results):  
    #This will be called (aka: it will run) after "aRoleName" completes "aStepName"
        for result in results:  # repeat the following actions for each result
            self.workflow.update_status(result, Status.COMPLETE)
    
if __name__ == '__main__':
    backend = StoreBackend()